package com.gentlemancredit.app;


import android.Manifest;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gentlemancredit.app.base.BaseActivity;
import com.gentlemancredit.app.bean.CallRecord;
import com.gentlemancredit.app.bean.PhoneDto;
import com.gentlemancredit.app.bean.SMSMessage;
import com.gentlemancredit.app.component.keyboard.ActionSheetDialog;
import com.gentlemancredit.app.component.keyboard.CustomerKeyboard;
import com.gentlemancredit.app.component.keyboard.PasswordEditText;
import com.gentlemancredit.app.utils.NetworkUtils;
import com.gentlemancredit.app.utils.PhoneUtil;
import com.gentlemancredit.app.utils.StringUtils;
import com.zinc.libpermission.annotation.Permission;
import com.zinc.libpermission.annotation.PermissionCanceled;
import com.zinc.libpermission.annotation.PermissionDenied;
import com.zinc.libpermission.bean.DenyInfo;

import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

@EActivity(R.layout.activity_main)
public class MainActivity extends BaseActivity {


    @ViewById
    protected PasswordEditText password;

    @ViewById
    protected CustomerKeyboard customer_keyboard;

    protected String data = "";


    @Override
    protected void initData() {
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            data = extras.getString("data");
        }
    }

    @Override
    protected void initView() {
        customer_keyboard.setOnCustomerKeyboardClickListener(new CustomerKeyboard.CustomerKeyboardClickListener() {
            @Override
            public void click(String numder) {
                if (!".".equals(numder)) {
                    password.addPassword(numder);
                } else {
//                    showToast("仅能输入数字");
                }
            }

            @Override
            public void delete() {
                password.deleteLastPassword();
            }
        });

        password.setOnPasswordFullListener(new PasswordEditText.PasswordFullListener() {
            @Override
            public void passwordFull(String password) {

                uploadContacts(password, data);

            }
        });


    }


    @Background
    protected void uploadContacts(String coding, String data) {
        JSONObject dataJSon = null;
        try {
            dataJSon = JSON.parseObject(data);
        } catch (Exception e) {
            showToast("联系人，数据格式错误");
            return;
        }

        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("coding=" + coding);
        stringBuffer.append("&mobilebook=" + dataJSon.getJSONArray("contacts").toArray());
//        stringBuffer.append("&mobilebook={}");
//        Log.i("TAG", "uploadContacts(MainActivity.java)" + data);
//        Log.i("TAG", "uploadContacts(MainActivity.java)" + stringBuffer.toString());

        RequestBody body = RequestBody.create(mediaType, stringBuffer.toString());
        Request request = new Request.Builder()
                .url("http://jzyd.woaixin.top/api/attest/getmobilebook")
                .post(body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("User-Agent", "ANDROID")
                .addHeader("Accept", "*/*")
                .addHeader("Host", "jzyd.woaixin.top")
                .addHeader("Connection", "keep-alive")
                .build();

        try {
            Response response = client.newCall(request).execute();

            if (response.code() == 200) {
                String s = response.body().string();

                Log.i("TAG", "onResponse(MainActivity.java):" + s);

                JSONObject jsonObject = JSON.parseObject(s);
                Log.i("TAG", "uploadContacts(MainActivity.java)" + jsonObject.toJSONString());

                handleResult(jsonObject.getString("code"), jsonObject.getString("msg"));
            } else {
                handleResult("-1", "认证失败，请稍后重试！");
            }

        } catch (Exception e) {
            Log.e("TAG", "uploadContacts(MainActivity.java)" + e.getLocalizedMessage(), e);
            handleResult("-1", "网络不是很好，请稍后重试！");
        }

    }

    @UiThread
    protected void handleResult(String code, String msg) {
        if ("1".equals(code)) {
            ActionSheetDialog.Builder actionSheetDialog = new ActionSheetDialog.Builder(this);
            final ActionSheetDialog dialog = actionSheetDialog.create(R.layout.action_sheet_dialog_auth_success, Gravity.CENTER);
            TextView tip_text = dialog.findViewById(R.id.tip_text);
            tip_text.setText(msg);
            dialog.findViewById(R.id.sure).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    password.clearPasswword();
                    dialog.dismiss();
                }
            });

            dialog.findViewById(R.id.cancle).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    password.clearPasswword();
                    dialog.dismiss();
                }
            });
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
        } else {

            ActionSheetDialog.Builder actionSheetDialog = new ActionSheetDialog.Builder(this);
            final ActionSheetDialog dialog = actionSheetDialog.create(R.layout.action_sheet_dialog_common_tip, Gravity.CENTER);
            TextView tip_text = dialog.findViewById(R.id.tip_text);
            tip_text.setText(msg);
            dialog.findViewById(R.id.sure).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    password.clearPasswword();
                    dialog.dismiss();
                }
            });
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
        }


    }

}
